import React from 'react';
import { connect } from 'react-redux';
import { Form, Icon, Input, Button ,Radio, message,Upload ,Modal} from 'antd';
import AdminUsersSelector  from '../users/AdminUsersSelector' ;
import { saveItembank ,fetchItembank } from "../../../actions/itembankActions";
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Dragger = Upload.Dragger;
import './style.css';
var _ = require('lodash');
class AddItembankForm extends React.Component{
    constructor(props){
      super(props);
      this.state = {
          value: 1,
          name:"", 
          limited :false,
          image:"",
          showUsersSeletor: false,
          previewVisible: false,
          previewImage:'',
          fileList:[],
          defaultTargetKeys:[],
      }
    }

    componentWillMount(){
        if ( this.props.initID ) {
            this.props.fetchItembank(this.props.initID).then(
                (res) => { 
                    let fileList = [{
                        uid: -1,
                        name: res.data.body.itembank.image,
                        status: 'done',
                        url: res.data.body.itembank.image, 
                    }];

                    var targetKeys = res.data.body.itembank.users || res.data.body.itembank.groups || res.data.body.itembank.tags || [];
                    if  (!(_.isEmpty(targetKeys))) {
                        targetKeys = targetKeys.map((item)=>{
                            return item.id
                        })
                    }

                    this.setState({
                        ...res.data.body.itembank,
                        fileList,
                        defaultTargetKeys:targetKeys    
                    });
                }
            )
        }
    }

    handleUploadChange = ({ fileList }) => {
        fileList = fileList.map((file) => {
            if (file.response) {
                file.url = file.response.url;
            }
            return file;
        });
        this.setState({fileList});
    } 
    
    handleCancel = () => this.setState({ previewVisible: false })

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }

    beforeUpload = (file) => {
        const isJPG = file.type === 'image/jpeg';
        if (!isJPG) {
            message.error('You can only upload JPG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJPG && isLt2M;
    }

    handleSubmit = (e) => {
        e.preventDefault();
        var id = parseInt(this.props.initID,10); //如果有初始ID，则是修改状态，否则则为创建状态
        this.props.form.validateFields((err, values) => {
            id = id || 0 ;
            let data = {id,...values};
                if (!(_.isEmpty(this.state.fileList[0]))) {
                    data["image"] = this.state.fileList[0].url
                }
            if (_.isEmpty(values.allow.keys)) {
                values.allow.type = this.state.allow_type;
                values.allow.keys = this.state.defaultTargetKeys;
            }
            if (!err) {
                    this.props.saveItembank(data).then(
                        (res) =>{ this.props.onSubmit(res.data.body); },
                        (err) => { message.success('创建题库失败'); }
                    )
            }
        });
   }

   handleRadioChange = (e) =>{
       if (e.target.value){
           this.setState({limited:true});
       }else {
           this.setState({limited:false});
       }
   }
   

   render(){
        const { getFieldDecorator } = this.props.form;
        const { previewVisible, previewImage, fileList } = this.state;
        /*const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
            </div>
        );*/
        return (
            <div className="add-itembank-form input-form">
                 <div className="clearfix">
                    <Dragger
                        name="itembank-image"
                        action="http://localhost:8080/api/upload"
                        listType="picture-card"
                        fileList={fileList}
                        beforeUpload={this.beforeUpload}
                        headers={ {Authorization: 'Bearer ' + localStorage.jwtToken } }
                        onPreview={this.handlePreview}
                        onChange={this.handleUploadChange}  >
                        <p className="ant-upload-drag-icon">
                             <Icon type="inbox" />
                        </p>
                        <p className="ant-upload-text">Click or drag file to this area to upload</p>
                        <p className="ant-upload-hint">Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files</p>
                    </Dragger>
                    <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                        <img alt="example" style={{ width: '100%' }} src={previewImage} />
                    </Modal>
                </div>

                <div>
                    创建新题库
                </div>
                <Form onSubmit={this.handleSubmit} className="add-itembank-form">
                    <FormItem label="题库名称">
                        {getFieldDecorator('name', {
                            rules: [{ required: true, message: '请输入题库的名称' }],
                            initialValue:this.state.name
                        })(
                            <Input addonBefore={<Icon type="database" />} placeholder="Username" />
                        )}
                    </FormItem>
                    <FormItem label="开放人群">
                        {getFieldDecorator('limit', {
                            rules: [{ required: true, message: '' }],
                            initialValue:this.state.limited
                        })(
                        <RadioGroup onChange={this.handleRadioChange}>
                            <Radio value={false}>公开</Radio>
                            <Radio value={true}>指定用户</Radio>
                        </RadioGroup>
                        )}
                    </FormItem>
                    {/*todo : 应该解决required=true的问题，如果没有选择用户，则不能提交*/}
                     { this.state.limited ?
                        <FormItem label="指定用户"> 
                            {getFieldDecorator('allow', { 
                                rules: [{ required: true, message: '请指定可访问用户' }],
                                initialValue:{type:this.state.allow_type,data:this.state.defaultTargetKeys}
                                })(  
                                    <AdminUsersSelector values={[]}/> 
                                    )}
                        </FormItem> : null }
                    <Button type="primary" htmlType="submit" className="login-form-button">
                        提交
                    </Button>
                </Form>
        </div>
    );
    }
}

const mapStateToProps = (state) => {
  return {
     createResult: state.itembank.createBankSuccessful,
   }
}

AddItembankForm.propTypes = {
    saveItembank: React.PropTypes.func.isRequired,
    fetchItembank:  React.PropTypes.func.isRequired,
};

export default connect(mapStateToProps,{saveItembank,fetchItembank})(Form.create()(AddItembankForm));